# -*- coding: utf-8 -*-
# @file    : context.py
# @Date    : 2020/11/11
# @Author  :
# @Version : 1.0.0
import threading
import weakref


class Context(object):
    """
    不同线程中维护不同的属性值
    """
    _weak_ref = weakref.WeakKeyDictionary()

    @property
    def _current_thread(self):
        return threading.current_thread()

    @property
    def __dict__(self):
        try:
            return self._get_current_dict()
        except RuntimeError:
            raise AttributeError("__dict__")

    def _get_current_dict(self):
        th = threading.current_thread()
        if th not in self._weak_ref:
            self._weak_ref[th] = {}
        return self._weak_ref[th]

    def __setattr__(self, key, value):
        self.__dict__[key] = value

    def __getattr__(self, key):
        return self.__dict__[key]

    def __delattr__(self, key):
        del self.__dict__[key]

    def __repr__(self):
        return "Context(th=%r)" % self._current_thread


context = Context()

if __name__ == '__main__':
    print(context)
